import React, { useState, useEffect } from "react";
import styles from "./index.less";
import {
  Card,
  Table,
  Button,
  Input,
  Space,
  Form,
  Modal,
  message,
  Popconfirm,
  List,
  Tooltip,
} from "antd";
import {
  PlusOutlined,
  SearchOutlined,
  DeleteOutlined,
  ArrowLeftOutlined,
  CommentOutlined,
  VerticalAlignBottomOutlined,
  PlusSquareOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { auth } from "@/utils/auth";
import moment from "moment";
interface UserData {
  key: string;
  username: string;
  devices: any;
  createdAt: string;
  userId: string;
}

interface ChatRecord {
  sessionId: string;
  username: string;
  content: string;
  lastMessageTime: string;
}

interface ChatMessage {
  username: string;
  role: string;
  content: string;
  createdAt: string;
}

interface CodesInfo {
  auditNumber: string;
  verifyCode: string;
}

const UsersPage: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isChatModalVisible, setIsChatModalVisible] = useState(false);
  const [createForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [chatLoading, setChatLoading] = useState(false);
  const [currentUser, setCurrentUser] = useState<UserData | null>(null);
  const [chatData, setChatData] = useState<ChatRecord[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [data, setData] = useState<UserData[]>([]);
  const [isChatDetailVisible, setIsChatDetailVisible] = useState(false);
  const [selectedUserChats, setSelectedUserChats] = useState<ChatMessage[]>([]);
  const [selectedUsername, setSelectedUsername] = useState("");
  const [searchParams, setSearchParams] = useState({
    username: "",
    deviceSerialNumber: "",
  });
  const [codes, setCodes] = useState<CodesInfo[]>([]);
  const [generateLoading, setGenerateLoading] = useState(false);
  const [isGenerateModalVisible, setIsGenerateModalVisible] = useState(false);

  const [exportLoading, setExportLoading] = useState(false);

  // 获取用户列表数据
  const fetchUserList = async (page: number = pagination.current) => {
    try {
      setLoading(true);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        limit: pagination.pageSize.toString(),
        role: "",
        isActive: "",
        createdAfter: "",
        search: searchParams.username,
        deviceSerialNumber: searchParams.deviceSerialNumber,
      });

      const response = await fetch(
        `/agentapi/users?${queryParams.toString()}`,
        {
          method: "GET",
          headers: {
            Authorization: `Bearer ${await auth.getValidAccessToken()}`,
          },
        }
      );

      if (response.status === 200) {
        const result = await response.json();
        if (Array.isArray(result.data)) {
          const formattedData = result.data.map((item: any) => ({
            key: item.id,
            username: item.displayName,
            devices: item.devices || [],
            createdAt: item.createdAt,
            userId: item.id,
          }));
          setData(formattedData);
          setPagination({
            current: page,
            pageSize: pagination.pageSize,
            total: result.pagination?.total || 0,
          });
        } else {
          message.error(result.message || "获取用户列表失败");
        }
      } else {
        message.error("获取用户列表失败");
      }
    } catch (error) {
      message.error("获取用户列表失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    // fetchUserList(1);
  }, []); // 只在组件挂载时执行一次

  // 当搜索参数变化时，重新获取数据
  useEffect(() => {
    fetchUserList(1);
  }, [searchParams]);

  const handleDelete = async (record: UserData) => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(`/agentapi/users/${record.userId}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      if (response.status === 204) {
        message.success("删除成功");
        fetchUserList(); // 重新获取列表
      } else {
        message.error("删除失败");
      }
    } catch (error) {
      message.error("删除失败，请检查网络连接");
    }
  };

  // 获取聊天记录
  const fetchChatRecords = async (userId: string) => {
    try {
      setChatLoading(true);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(`/agentai/chat/session/${userId}`, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          setChatData(result.data);
        } else {
          message.error(result.message || "获取会话列表失败");
        }
      } else {
        message.error("获取会话列表失败");
      }
    } catch (error) {
      message.error("获取会话列表失败，请检查网络连接");
    } finally {
      setChatLoading(false);
    }
  };

  const showChatModal = (record: UserData) => {
    setCurrentUser(record);
    setIsChatModalVisible(true);
    fetchChatRecords(record.key);
  };

  const handleChatModalCancel = () => {
    setIsChatModalVisible(false);
    setCurrentUser(null);
    setChatData([]);
  };

  const handleChatItemClick = async (record: ChatRecord) => {
    try {
      setSelectedUsername(record.username);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(
        `/agentai/chat/${currentUser?.key}?sessionId=${record.sessionId}`,
        {
          headers: {
            Authorization: `Bearer ${await auth.getValidAccessToken()}`,
          },
        }
      );

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          const formattedMessages = result.data.map((msg: ChatMessage) => ({
            id: msg.createdAt,
            username: msg.role === "user" ? msg.username : "AI分身",
            content: msg.content,
            createdAt: msg.createdAt,
          }));
          setSelectedUserChats(formattedMessages);
        } else {
          message.error(result.message || "获取聊天记录失败");
        }
      } else {
        message.error("获取聊天记录失败");
      }
    } catch (error) {
      message.error("获取聊天记录失败，请检查网络连接");
    }
    setIsChatDetailVisible(true);
    setIsChatModalVisible(false);
  };

  const handleBackToList = () => {
    setIsChatDetailVisible(false);
    setIsChatModalVisible(true);
  };

  const handleSearch = (values: any) => {
    setSearchParams({
      username: values.search || "",
      deviceSerialNumber: values.deviceSerialNumber || "",
    });
  };

  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({
      username: "",
      deviceSerialNumber: "",
    });
  };

  const handleGenerate = async () => {
    try {
      setGenerateLoading(true);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch("/agentapi/audit-codes/generate-batch", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
        body: JSON.stringify({
          count: 20,
        }),
      });

      if (response.status === 201) {
        message.success("审核码生成成功");
        const result = await response.json();
        setCodes(result.codes);
        setIsGenerateModalVisible(true);
      } else {
        message.error("审核码生成失败");
      }
    } catch (error) {
      message.error("审核码生成失败，请检查网络连接");
    } finally {
      setGenerateLoading(false);
    }
  };

  const handleExport = async () => {
    try {
      setExportLoading(true);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;
      const response = await fetch(`/agentapi/audit-codes/export`, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          return response.text(); // 或者 response.json() 如果返回的是JSON需要转换
        })
        .then((csvData) => {
          const blob = new Blob([csvData], { type: "text/csv;charset=utf-8;" });
          const link = document.createElement("a");
          const url = URL.createObjectURL(blob);
          link.setAttribute("href", url);
          link.setAttribute("download", "data.csv");
          link.style.visibility = "hidden";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        });
    } catch (error) {
      message.error("下载失败，请检查网络连接");
    } finally {
      setExportLoading(false);
    }
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    createForm.resetFields();
  };

  const handleCreate = async () => {
    try {
      const values = await createForm.validateFields();
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch("/agentapi/users", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
        body: JSON.stringify({
          username: values.username,
          password: "r54VmfYv",
          role: "user",
        }),
      });

      if (response.status === 201) {
        const result = await response.json();
        message.success("创建成功");
        setIsModalVisible(false);
        createForm.resetFields();
        fetchUserList(); // 重新获取列表
      } else {
        message.error("创建失败");
      }
    } catch (error) {
      message.error("创建失败，请检查网络连接");
    }
  };

  const columns: ColumnsType<UserData> = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "设备号",
      dataIndex: "devices",
      key: "devices",
      render: (devices) => {
        if (!devices || !Array.isArray(devices) || devices.length === 0) {
          return "无";
        }
        let serialNumbers = devices.map((i: any) => i.serialNumber || "未知");
        return serialNumbers.join("，");
      },
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (createdAt) => {
        return moment.utc(createdAt).format("YYYY-MM-DD HH:mm:ss");
      },
    },
    {
      title: "其他",
      key: "actions",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<CommentOutlined />}
            onClick={() => showChatModal(record)}
          >
            AI记录
          </Button>
        </Space>
      ),
    },
    {
      title: "操作",
      key: "operation",
      render: (_, record) => (
        <Popconfirm
          title="删除用户"
          description="确定要删除这个用户吗？此操作不可恢复。"
          onConfirm={() => handleDelete(record)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" danger icon={<DeleteOutlined />}>
            删除
          </Button>
          
        </Popconfirm>
      ),
    },
  ];

  return (
    <div className={styles.container}>
      <Card>
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <Form
            form={searchForm}
            layout="inline"
            onFinish={handleSearch}
            className={styles.searchForm}
          >
            {/* <Form.Item name="search">
              <Input
                placeholder="请输入用户名"
                prefix={<SearchOutlined />}
                allowClear
              />
            </Form.Item> */}
            <Form.Item name="deviceSerialNumber">
              <Input
                placeholder="设备号"
                prefix={<SearchOutlined />}
                allowClear
              />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button onClick={handleReset}>重置</Button>
                <Tooltip title="生成审核码">
                  <Popconfirm
                    title="生成审核码"
                    description="请确认是否批量生成审核码?"
                    okText="生成"
                    cancelText="取消"
                    onConfirm={handleGenerate}
                    okButtonProps={{ loading: generateLoading }}
                  >
                    <Button
                      variant="filled"
                      color="primary"
                      icon={<PlusSquareOutlined />}
                    />
                  </Popconfirm>
                </Tooltip>

                <Tooltip title="下载审核码">
                  <Button
                    variant="filled"
                    color="primary"
                    icon={<VerticalAlignBottomOutlined />}
                    onClick={handleExport}
                    loading={exportLoading}
                  />
                </Tooltip>
              </Space>
            </Form.Item>
          </Form>
          <div className={styles.tableHeader}>
            <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
              新建用户
            </Button>
          </div>
        </div>

        <Table<UserData>
          columns={columns}
          dataSource={data}
          rowKey="key"
          loading={loading}
          style={{
            height: `calc(100vh - 260px)`,
            overflow: "auto",
            scrollbarWidth: "none",
          }}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page) => fetchUserList(page),
          }}
        />

        <Modal
          title="创建用户"
          open={isModalVisible}
          onOk={handleCreate}
          onCancel={handleCancel}
          confirmLoading={loading}
          okText="确定"
          cancelText="取消"
        >
          <Form
            form={createForm}
            layout="horizontal"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: "请输入用户名" }]}
            >
              <Input placeholder="请输入用户名" />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="AI聊天记录"
          open={isChatModalVisible}
          onCancel={handleChatModalCancel}
          footer={null}
          width={600}
        >
          <List
            style={{
              maxHeight: "500px",
              overflow: "auto",
              scrollbarWidth: "none",
            }}
            loading={chatLoading}
            dataSource={chatData}
            renderItem={(item) => (
              <List.Item
                style={{ cursor: "pointer" }}
                onClick={() => handleChatItemClick(item)}
              >
                <List.Item.Meta title={item.username} />
                <div>
                  {moment.utc(item.lastMessageTime).format("YYYY-MM-DD HH:mm:ss")}
                </div>
              </List.Item>
            )}
          />
        </Modal>

        <Modal
          title="审核码"
          open={isGenerateModalVisible}
          footer={null}
          width={400}
          onCancel={() => {
            setIsGenerateModalVisible(false);
          }}
        >
          <List
            style={{
              maxHeight: "500px",
              overflow: "auto",
              scrollbarWidth: "none",
            }}
            loading={chatLoading}
            dataSource={[
              { auditNumber: "审核编号", verifyCode: "校验码" },
              ...codes,
            ]}
            renderItem={(item, index) => (
              <List.Item>
                <div style={{ width: 40, marginTop: -5 }}>
                  {index > 0 && index}
                </div>
                <List.Item.Meta title={item.auditNumber} />
                <List.Item.Meta title={item.verifyCode} />
                {/* <div>{item.verifyCode}</div> */}
              </List.Item>
            )}
          />
        </Modal>

        <Modal
          title={
            <Space>
              <Button
                icon={<ArrowLeftOutlined />}
                type="link"
                onClick={handleBackToList}
              />
              {selectedUsername}的聊天记录
            </Space>
          }
          open={isChatDetailVisible}
          onCancel={() => setIsChatDetailVisible(false)}
          footer={null}
          width={600}
        >
          <List
            dataSource={selectedUserChats}
            style={{
              maxHeight: "500px",
              overflow: "auto",
              scrollbarWidth: "none",
            }}
            renderItem={(item) => (
              <List.Item>
                <List.Item.Meta
                  title={
                    <Space>
                      <span>{item.username}</span>
                      <span style={{ color: "#999", fontSize: "12px" }}>
                        {moment.utc(item.createdAt).format("YYYY-MM-DD HH:mm:ss")}
                      </span>
                    </Space>
                  }
                  description={item.content}
                />
              </List.Item>
            )}
          />
        </Modal>
      </Card>
    </div>
  );
};

export default UsersPage;
